<template>
  <div>
    <a-spin :spinning='showTable'>
      <div class='btn-content' v-if='isAction'>
        <span class='nor-btn' :class='{"btn-dis": btnDisable}' @click='add'>新增交付物要求</span>
        <span class='nor-btn' :class='{"btn-dis": btnDisable}' @click='update'>编辑</span>
        <span class='nor-btn' :class='{"btn-dis": btnDisable}' @click='del'>移除</span>
        <span class='nor-btn' :class='{"btn-dis": btnDisable}' @click='startCensor'>启动签审</span>
      </div>
      <a-table :columns="deliverCols" :data-source="source" :pagination='false'
        :row-selection="selRows">
        <template v-for="item in slotColumns" :slot="item.dataIndex" slot-scope="text,record,index">
          <component :is="item.slotType" :key="`${item.dataIndex}-${record.id}`" :data='record'
            :index='index' :updateRows='updateRows' :isLook='isLook' :uploadAction='!btnDisable'
            :columnInfo='item' @setUpdateData='setUpdateDataHandler(arguments,record)'
            @upload='uploadHandler(record)' @delDeliver='delDeliverHandler(record)'/>
        </template>
      </a-table>
    </a-spin>
    <upload-delivery :upload-modal-visible="uploadVisible"
      @submitDeliver='submitDeliverHandler'  @closeUploadModal='closeUploadModal'></upload-delivery>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import copyACtion from '@/views/singleProject/fileSingle/el-common-js/copy'
import { getDeliverInfo,updateDeliverInfo,createDeliverInfo,deleteDeliverInfo,submitDeliverSubject } from "@api/planComponent";
import showspan from './components/showspan'
import upload from './components/upload'
import uploadDelivery from '@/components/uploadDelivery/index'
export default {
  mixins: [copyACtion],
  components: {
    showspan,
    upload,
    uploadDelivery
  },
  props: {
    deliverCols: {
      type: Array,
      default: () => []
    },
    isAction: {
      type: Boolean,
      default: false
    },
    isLook: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapGetters({
      isAddNode: 'isAddNode',
    }),
    slotColumns() {
      return this.deliverCols.filter(item => item.slotType != undefined)
    },
    selRows() {
      return this.isAction ? { selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange } : null
    },
    btnDisable() {
      return this.task.plannableStatus != undefined && this.task.plannableStatus == 'COMPLETED'
    }
  },
  data() {
    return {
      showTable: true,
      uploadVisible: false,
      source: [],
      selectedRowKeys: [],
      updateRows: [],
      updateMap: new Map(),
      task: '',
      uploadDeliver: '',
    }
  },
  methods: {
    //弹出上传框
    uploadHandler(data) {
      this.uploadVisible = true;
      this.uploadDeliver = data;
    },
    //删除交付物
    delDeliverHandler(data) {
      this.uploadDeliver = data;
      //修改数据
      this.submitDeliverHandler({
        name: '',
        oid: '',
        state: ''
      });
    },
    //启动签审
    startCensor() {
      if (this.btnDisable)
        return
      if (this.selectedRowKeys.length == 0) {
        this.$message.error('请选中交付物后,进行签审!');
        return;
      }
      let tempList = []
      for (let i = 0; i < this.selectedRowKeys.length; i++) {
        let data = JSON.parse(JSON.stringify(this.source[this.selectedRowKeys[i]]));
        data.oid = data.subjectOid
        if (data.subjectState != '正在工作' && data.subjectState != '重新工作') {
          this.$message.error('请选择正在工作或者重新工作的交付物进行签审!');
          return;
        }
        if (data.oid != '' && data.oid.indexOf('ProjectTaskBook') != -1) {
          this.$message.error('您选中的内容包含任务书，请创建立项评审发布项目任务书!');
          return;
        }
        if (data.oid != '' && data.oid.indexOf('ProjectTaskBook') == -1 
              && data.oid.indexOf('WTDocument') == -1) {
          this.$message.error('您选中的内容包含任务书，请创建立项评审发布项目任务书!');
          return;
        }
        tempList.push(data)
      }
      let sessArr = {
        tableArr:tempList
      }
      sessionStorage.setItem('fileSingleDataByStart',JSON.stringify(sessArr))
      this.$router.push('fileSingle/fileStart');
    },
    getDetails(task) {
      this.task = JSON.parse(JSON.stringify(task))
      this.selectedRowKeys = []
      this.updateMap = new Map();
      this.updateRows = []
      this.getNetDetail()
    },
    getNetDetail(fn = null) {
      this.showTable = true;
      if (this.isAddNode(this.task.oid)) {
        this.showTable = false;
      }else {
        getDeliverInfo({
          oid: this.task.oid
        }).then(res => {
          this.showTable = false;
          this.source = res.data.data.length == 0 ? [] : res.data.data
          fn && fn();
        })
      }
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    add() {
      if (this.btnDisable)
        return
      if (this.isAddNode(this.task.oid)) {
        this.$message.error('新增任务需保存后,才能进行交付物操作!')
        return 
      }
      if (this.source.some(item => item.simpleOid == undefined || item.simpleOid == '')) {
        this.$message.error('每次只能新增一个交付物')
        return 
      }
      this.updateRows.push(this.source.length)
      const oid = `add-${this.source.length}`;
      this.source.push({
        isLatestVersion: '',
        name: '',
        oid ,
        subjectName: '',
        subjectOid: '',
        subjectState: '',
      })
      this.updateMap.set(oid,{
        name: '',
        subjectOid: ''
      })
    },
    update() {
      if (this.btnDisable)
        return
      if(this.selectedRowKeys.length == 1) {
        if(!this.updateRows.includes(this.selectedRowKeys[0]))
          this.updateRows.push(this.selectedRowKeys[0])
      }else {
        this.$message.error('只能选择一行数据进行编辑!')
      }
    },
    del() {
      if (this.btnDisable)
        return
      if(this.selectedRowKeys.length > 0) {
        let ids = []
        const delIds = this.selectedRowKeys.sort((pre,next) => next - pre);
        this.source.forEach((item,index) => {
          if (this.selectedRowKeys.includes(index) && item.oid.indexOf('add') == -1)
            ids.push(item.oid)
        })
        this.showTable = true;
        deleteDeliverInfo({
          oid: this.task.oid,
          oids: JSON.stringify(ids)
        }).then(res => {
          this.showTable = false;
          if(res.data.success == 'true') {
            //删除移除的数据
            this.selectedRowKeys = []
            delIds.forEach(item => {
              this.source.splice(item,1);
            })
            this.$message.success('移除成功!')
            this.backTableData();
          }else {
            this.$message.error(res.data.message)
          }
        })
      }else {
        this.showTable = false;
        this.$message.error('请选中交付物后进行移除!')
      }
    },
    //设置表格数据
    backTableData() {
      this.updateMap = new Map();
      let value = [];
      this.source.forEach(item => {
        value.push({
          deliverableId: item.simpleOid,
          deliverableName: item.name,
          taskId: this.task.oid
        })
      })
      this.$emit('update',value,'deliverable',this.task)
    },
    //设置修改的数据
    setUpdateDataHandler([key,value],record) {
      let result = this.updateMap.get(record.oid)
      if(result == undefined) {
        result = {
          name: '',
          subjectOid: ''
        }
      }
      result[key] = value
      this.updateMap.set(record.oid,result)
    },
    //修改 新增数据
    submitData(fn) {
      const self = this;
      if(Array.from(self.updateMap).some(item => item[1].name == '')){
        self.$message.error('请输入交付物名称')
        return
      }
      if(self.updateMap.size > 0) {
        self.selectedRowKeys = []
        self.updateRows = []
        let requests = []
        for(let [key,value] of self.updateMap.entries()) {
          if (key.indexOf('add') != -1) {
            //新建交付物
            requests.push(
            createDeliverInfo({
              oid: self.task.oid,
              ...value
            }))
          }else {
            //修改数据
            requests.push(
            updateDeliverInfo({
              oid: key,
              ...value
            }))
          }
        }
        Promise.all(requests).then(res => {
          self.getNetDetail(() => {
            self.$message.success('新增,修改交付物成功!')
            self.backTableData()
            fn();
          })
        })
      }else
        fn();
    },
    //关闭上传交付物弹窗
    closeUploadModal() {
      this.uploadVisible = false
    },
    //设置交付物
    submitDeliverHandler(subjectData,isFolder) {
      submitDeliverSubject({
        oid: this.task.oid,
        deliverableOid: this.uploadDeliver.oid,
        subjectOid: subjectData.oid
      }).then(res => {
        this.uploadDeliver.isLatestVersion = '是';
        this.uploadDeliver.subjectName = subjectData.name;
        this.uploadDeliver.subjectOid = subjectData.oid;
        this.uploadDeliver.subjectState = subjectData.state;
        this.$set(this.source,this.source.findIndex(item => item.oid == res.data.data[0]),this.uploadDeliver)
        this.$message.success(subjectData.oid == '' ? '以删除交付物' : '添加交付物成功!')
        this.closeUploadModal();
      })
    }
  }
}
</script>
<style scoped lang='less'>
.btn-dis {
  color: rgba(0, 0, 0, 0.25);
  background-color: #f5f5f5 !important;
  border-color: #d9d9d9;
  cursor: no-drop !important;
}
.btn-content {
  margin: 10px 0;
  .nor-btn {
    display: inline-block;
    padding: 0 10px;
    border: 1px solid #ccc;
    border-radius: 3px;
    margin-right: 10px;
    line-height: 28px;
    cursor: pointer
  }
  .nor-btn:not(.btn-dis):hover{
    background: #386bd7;
    color: #fff;
    border-color: #386bd7;
  }
}
</style>